<?php

/*
Plugin to get data from Google Refine to display edit history on a Google Refine "Project"

This class posts a small JSON string of authorization data to the Google Refine server.
*/

class HTTPclient {
    
    public $authorized; //authorization token for HTTP header
    public $message; //message to post
    public $refineBaseURI; //uri of google refine.
    public $postActionURI; //location (suffix) to post the data.
    
    public $success; //success
    public $errorMessage; //error
    public $responseInfo; //information about the response
    
    public $responseData; //data from the response to the POST request
    public $postURI; //where the post message was actually sent.
    
    public function postData(){
        
        $this->success = false; //assume the worst!
        $postURI = $this->refineBaseURI.($this->postActionURI); //location for POST
        $this->postURI = $postURI;
        
        $postData = $this->prepPostData($this->message);
        
        $headers = array(
                        //"Content-Type: application/json",
                        "AUTHORIZATION: ".$this->authorized,
                        "Content-length: ".strlen($postData));
        
        $tuCurl = curl_init();
        
        $postData = $this->prepPostData($this->message);
        
        curl_setopt($tuCurl, CURLOPT_POST, true);
        curl_setopt($tuCurl, CURLOPT_POSTFIELDS, $postData);
        curl_setopt($tuCurl, CURLOPT_HEADER, false);
        curl_setopt($tuCurl, CURLOPT_HTTPHEADER, $headers);
        curl_setopt($tuCurl, CURLOPT_URL, $postURI);
        curl_setopt($tuCurl, CURLOPT_RETURNTRANSFER, 1); 
        curl_setopt($tuCurl, CURLOPT_VERBOSE, 1);
        //curl_setopt($tuCurl, CURLOPT_HEADER, false); 
        //curl_setopt($tuCurl, CURLOPT_POSTFIELDS, $this->message);
        //curl_setopt($tuCurl, CURLOPT_NOBODY, true);
        //curl_setopt($tuCurl, CURLOPT_POSTFIELDS, urlencode($this->message));
        

        $this->responseData = curl_exec($tuCurl); 
        if(!curl_errno($tuCurl)){ 
            $info = curl_getinfo($tuCurl);
            $this->success = true;
            $this->responseInfo = $info;
        } else { 
            $this->errorMessage = curl_error($tuCurl); 
        } 
        
        curl_close($tuCurl);
        
    }//end function


    function prepPostData($postArray){
        
        $postString = "";
        $firstLoop = true;
        foreach($postArray as $key => $value){
            $parameterItem = urlencode($key)."=".urlencode($value);
            if($firstLoop){
                $postString .=  $parameterItem;
            }
            else{
                $postString .=  "&".$parameterItem;
            }
            $firstLoop = false; 
        }
       return $postString;
    }



}//end class

?>